package com.library.service;



import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;
import java.sql.Statement;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.library.common.HibernateSessionFactory;
import com.library.dao.ICommonDAO;
import com.library.model.Bookinfo;



public class BookService {
	private ICommonDAO commonDao;
	private Bookinfo book = new Bookinfo();
	public void doborrow(int bookid,int userid){
		update_userid(bookid, userid);
		Session session= HibernateSessionFactory.getSession();
		String hql = "from Bookinfo b where b.bookid="+bookid;
		List list = (List) commonDao.list(hql);
		if(list.size()!=0&&list!=null){	
				Transaction  tx = session.beginTransaction();
				book = (Bookinfo) list.get(0);
				book.setStatus(-1);
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
				long time=0;
				int day=30;
				Date today=new Date();
				time=(today.getTime()/1000)+60*60*24*day;
				book.setStarttime(today);
				Date newDate=new Date();
				newDate.setTime(time*1000); 
				book.setEndtime(newDate);
				session.update(book);
				tx.commit();
			
			}
	}
	public void update_userid(int bookid,int userid){
		Connection con = null;
		Statement stmt = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/library?user=root&password=");
			stmt = con.createStatement();
			String sql = "update bookinfo b set b.userid = "+userid+" where b.bookid="+bookid;
			stmt.executeUpdate(sql);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if(con!=null){
					con.close();
					con=null;
					}
					if(stmt!=null){
						stmt.close();
						stmt=null;
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		
	}
	public ICommonDAO getCommonDao() {
		return commonDao;
	}

	public void setCommonDao(ICommonDAO commonDao) {
		this.commonDao = commonDao;
	}
	
}
